package sanshui.system.trade.config;

import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import sanshui.system.trade.common.CommonResponse;
import sanshui.system.trade.common.GlobalContain;
import sanshui.system.trade.factory.trade.TradeSystemExecutor;

import javax.annotation.PostConstruct;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Component
public class SpringContextHolder implements ApplicationContextAware {
    private static Logger log = LoggerFactory.getLogger(SpringContextHolder.class);
    private static ApplicationContext applicationContext = null;

    @PostConstruct
    public CommonResponse<Boolean> createTradeSystem() {
        log.info("自动创建全局交易系统");
        GlobalContain.tradeSystemExecutor = new TradeSystemExecutor();
        GlobalContain.tradeSystemExecutor.init(100);

        ExecutorService threadPoolTrade = Executors.newFixedThreadPool(2);
        threadPoolTrade.submit(GlobalContain.tradeSystemExecutor::run);
        threadPoolTrade.submit(GlobalContain.tradeSystemExecutor::loadWorker);
        return CommonResponse.ok(true, "启动成功");
    }

    @Override
    public void setApplicationContext(@NotNull ApplicationContext applicationContext) throws BeansException {
        log.info("使用注解类context寻找Bean");
        SpringContextHolder.applicationContext = applicationContext;
    }

    public static <T> T getBean(Class<T> clazz) {
        return applicationContext.getBean(clazz);
    }
}
